package com.mouse.magent.common.codec;


import com.mouse.magent.common.protocol.Command;
import com.mouse.magent.common.protocol.Header;
import com.mouse.magent.common.protocol.Message;
import com.mouse.magent.common.util.JsonUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 序列化
 */
@Slf4j
public class MessageDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List out) throws Exception {
        int type = msg.readInt();
        Command natxMessageType = Command.valueOf(type);

        int metaDataLength = msg.readInt();
        CharSequence metaDataString = msg.readCharSequence(metaDataLength, CharsetUtil.UTF_8);
        Header header = JsonUtil.toObject(metaDataString.toString(), Header.class);
        byte[] data = null;
        if (msg.isReadable()) {
            data = ByteBufUtil.getBytes(msg);
        }
        Message message = new Message();
        message.setType(natxMessageType);
        message.setHeader(header);
        log.info("message接收：{} data大小:{}", JsonUtil.toJson(message), message.getData() == null ? 0 : data.length);
        message.setData(data);
        out.add(message);
    }

}
